package com.xc.utils.email;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Calendar;
import java.util.List;

import com.xc.common.Const;
import com.xc.pojo.User;
import com.xc.pojo.UserRecharge;
import com.xc.utils.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * @author mipha
 * @version 1.0
 * @date 2019/3/7 7:38 PM
 */
@Slf4j
public class SendHTMLMail {
    public static void main(String[] args) {
//        SendHTMLMail.send();
    }

    /**
     *  发送审核邮件
     * @param user
     * @param userRecharge
     */
    public static void send(User user , UserRecharge userRecharge
            ,String emailToken,String host,String emailTo){

        SAXReader reader = new SAXReader();
        Document document = null;

        //  这里是获取到 /target/classes 路径 （替换 %20）
        String path = SendHTMLMail.class.getResource("/").getPath().replaceAll("%20", " ");
//        log.info("发送邮件 path = {}" , path);
        String html_path = path + "email/auth.html";
//        log.info("发送邮件 html_path = {}" , html_path);

//        System.out.println("path = " + path);
        File file = new File(html_path);
        try {
            //获取模板html文档
            document = reader.read(file);
            document.setXMLEncoding("utf-8");
            Element root = document.getRootElement();

            Element time = getNodes(root, "id", "time");
            Calendar calendar = Calendar.getInstance();
            time.setText(
                    calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)
                    + "-" + calendar.get(Calendar.DATE)+" " + (calendar.get(Calendar.HOUR))
                    + ":" + calendar.get(Calendar.MINUTE)  + ":" + calendar.get(Calendar.SECOND)
            );
            Element noticeName = getNodes(root, "id", "noticeName");
            noticeName.setText(user.getRealName());

            Element userid = getNodes(root, "id", "userid");
            userid.setText(user.getId()+"");
            Element realname = getNodes(root, "id", "realname");
            realname.setText(user.getAccountType() == 0
                    ? "正式用户 - " + user.getRealName()
                    : "模拟用户 - " + user.getRealName());
            Element amt = getNodes(root, "id", "amt");
            amt.setText(userRecharge.getPayAmt().toString());
            Element ordersn = getNodes(root, "id", "ordersn");
            ordersn.setText(userRecharge.getOrderSn());

            String authurl = PropertiesUtil.getProperty("site.email.auth.url");

            //  拼接链接
            String emailUrl = host + authurl + "?token=" + emailToken
                    + "&orderSn=" + userRecharge.getOrderSn()
                    + "&state=";

            String successUrl = emailUrl+ Const.UserRechargeStatus.charge_success;
            Element dosuccessurl = getNodes(root, "id", "dosuccessurl");
            dosuccessurl.setText(successUrl);
            Element dosuccess = getNodes(root, "id", "dosuccess");
            dosuccess.setAttributeValue("href",successUrl);

            String failUrl = emailUrl+ Const.UserRechargeStatus.charge_fail;
            Element dofailurl = getNodes(root, "id", "dofailurl");
            dofailurl.setText(failUrl);
            Element dofail = getNodes(root, "id", "dofail");
            dofail.setAttributeValue("href",failUrl);

            String cancelUrl = emailUrl+ Const.UserRechargeStatus.charge_cancel;
            Element docancelurl = getNodes(root, "id", "docancelurl");
            docancelurl.setText(cancelUrl);
            Element docancel = getNodes(root, "id", "docancel");
            docancel.setAttributeValue("href",cancelUrl);

            /**
             *  保存到临时文件
             */
            FileWriter fwriter = new FileWriter(path + "email/temp.html");
            XMLWriter writer = new XMLWriter(fwriter);
            writer.write(document);
            writer.flush();
            //读取临时文件，并把html数据写入到字符串str中，通过邮箱工具发送
            FileReader in = new FileReader(path + "email/temp.html");
            char[] buff = new char[1024 * 10];
            in.read(buff);
            String str = new String(buff);

            str = str.replaceAll("\u0000","");

            new MailSender.Builder(str.toString() , emailTo).send();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 方法描述：递归遍历子节点，根据属性名和属性值，找到对应属性名和属性值的那个子孙节点。
     * @param node 要进行子节点遍历的节点
     * @param attrName 属性名
     * @param attrValue 属性值
     * @return 返回对应的节点或null
     */
    public static Element getNodes(Element node, String attrName, String attrValue) {

        final List<Attribute> listAttr = node.attributes();// 当前节点的所有属性
        for (final Attribute attr : listAttr) {// 遍历当前节点的所有属性
            final String name = attr.getName();// 属性名称
            final String value = attr.getValue();// 属性的值

//            System.out.println("属性名称：" + name + "---->属性值：" + value);

            if(attrName.equals(name) && attrValue.equals(value)){
                return node;
            }
        }
        // 递归遍历当前节点所有的子节点
        final List<Element> listElement = node.elements();// 所有一级子节点的list
        for (Element e : listElement) {// 遍历所有一级子节点
            Element temp = getNodes(e,attrName,attrValue);
            // 递归
            if(temp != null){
                return temp;
            }
        }
        return null;
    }

}